<template>
  <view class="detail-wrap" v-if="playItem">
    <image class="bg1" :class="{active:bgToggle}" :src="linearColor1" mode="center"></image>
    <image class="bg2" :class="{active:bgToggle}"  :src="linearColor2" mode="center"></image>
 
    <view class="header">
      <uni-icons color="#fff" size="24" type="bottom"></uni-icons>
      <view class="info">
        <view v-if="playItem.name.length<8" class="name">
          {{playItem.name}}
        </view>
        <uni-notice-bar v-else :fontSize="16" background-color="rgba(0,0,0,0)" color="#fff" :speed="25" scrollable
          single :text="playItem.name"></uni-notice-bar>
        <view class="artist">
          {{playItem.ar[0].name}}
        </view>
      </view>
      <uni-icons color="#ffffff" size="24" custom-prefix="iconfont" type="icon-fenxiang"></uni-icons>
    </view>
    <!-- 轮播 -->
    <swiper @animationfinish="changeBg" :current="currenIndex" circular="true" :interval="3000"
      :duration="1000">
      <swiper-item v-for="item,index in swiperList" :key="index">
        <image ref="target" :id="`bg${index}`" class="bg" :class="{'pus_img':state}" :src="item.al.picUrl">
        </image>
      </swiper-item>
    </swiper>
    <!-- 控制 -->
    <view class="control">
      <!-- 进度条 -->
      <view class="time-box">
        <view class="start">
          {{formatTime(start)}}
        </view>
        <slider @change="stepMisic" :value="start" :max="end" backgroundColor="rgba(255,255,255,0.3)"
          activeColor="rgba(255,255,255,0.4)" block-color="rgba(255,255,255,0.5)" block-size="12" />
        <view class="end">
          {{formatTime(end)}}
        </view>
      </view>
      <!-- 按钮 -->
      <view class="icons">
        <uni-icons color="#ffffff" size="20" custom-prefix="iconfont" type="icon-suiji"></uni-icons>
        <uni-icons @click="toggle(-1)" color="#ffffff" size="20" custom-prefix="iconfont"
          type="icon-shangyishoushangyige"></uni-icons>
        <uni-icons @click="play('play')" v-if="state" color="#ffffff" size="34" custom-prefix="iconfont"
          type="icon-bofang1"></uni-icons>
        <uni-icons @click="play('pause')" v-else color="#ffffff" size="34" custom-prefix="iconfont"
          type="icon-zanting1"></uni-icons>
        <uni-icons @click="toggle(1)" color="#ffffff" size="20" custom-prefix="iconfont" type="icon-xiayigexiayishou">
        </uni-icons>
        <uni-icons color="#ffffff" size="18" custom-prefix="iconfont" type="icon-kongzhi"></uni-icons>
      </view>
    </view>
    <!-- <canvas type="2d" class="canvas" canvas-id="canvas" style="width: 100px; height: 100px;" id="canvas"></canvas> -->
  </view>
</template>

<script setup>
  import {
    audio
  } from '@/utils/audio.js'
  import {
    onLoad
  } from "@dcloudio/uni-app";
  import {
    computed,
    getCurrentInstance,
    nextTick,
    onMounted,
    onUnmounted,
    reactive,
    ref,
    watch
  } from "vue";
  // 播放状态默认播放
  const state = ref(false)
  // 播放列表
  const playList = ref([])
  // 播放序号
  const playIndex = ref(0)
  // 当前播放item
  const playItem = computed(() => {
    return playList.value[playIndex.value]
  })
  // 轮播list
  const swiperList = ref([])
  // 当前轮播index
  const currenIndex = ref(0)
  // 监听播放进度
  const end = ref(null)
  const start = ref(null)
  // 定义向前向后判断
  let direct = null
  // 全局播放器
  const music = audio
  const _this = getCurrentInstance()
  onLoad((option) => {
    const {
      index,
      songDetail
    } = JSON.parse(decodeURIComponent(option.item))
    playIndex.value = index
    if (songDetail[0].alg) {
      songDetail.forEach((item, index) => {
        item.al = {
          id: item.id,
          name: item.name,
          picUrl: item.picUrl
        }
        item.ar = [item.song.artists[0]]
      })
    }
    playList.value = songDetail
    linearColor1.value = playItem.value.al.picUrl
    music.src = `http://music.163.com/song/media/outer/url?id=${playItem.value.id}.mp3`
    getSwiperList()
  })
  // 轮播触发
  const toggleMusic = (e) => {
    state.value = false
    start.value = 0
    // currenIndex 初始位置
    let current = Number(e.detail.current) // 现在位置
    let flag
    if (e.detail.source === 'touch') {
      flag = current - currenIndex.value == -2 || current - currenIndex.value == 1 ? 1 : -1
      currenIndex.value = current
    } else {
      flag = direct
    }
    playIndex.value = getDateIndex(playIndex.value + flag)
    getSwiperList()
    // 切换数据
    // 修改播放器状态
    music.src = `http://music.163.com/song/media/outer/url?id=${playItem.value.id}.mp3`
  }
  const getSwiperList = () => {
    let currValue = playList.value[playIndex.value]
    let nextValue = playList.value[getDateIndex(playIndex.value + 1)]
    let prevValue = playList.value[getDateIndex(playIndex.value - 1)]
    swiperList.value[currenIndex.value] = currValue
    swiperList.value[getSwiperIndex(currenIndex.value + 1)] = nextValue
    swiperList.value[getSwiperIndex(currenIndex.value - 1)] = prevValue
  }

  const getDateIndex = (index) => {
    if (index < 0) {
      return playList.value.length - 1
    } else if (index >= playList.value.length) {
      return 0
    } else {
      return index
    }
  }
  const getSwiperIndex = (index) => {
    if (index < 0) {
      return 2
    } else if (index >= 3) {
      return 0
    } else {
      return index
    }
  }
  // 控制播放按钮
  const play = (str) => {
    if (str === 'play') {
      state.value = false
      music.play()
    } else {
      state.value = true
      music.pause()
    }
  }
  const toggle = (str) => {
    direct = str
    currenIndex.value = getSwiperIndex(currenIndex.value + str)
  }
  music.onEnded(() => {
    toggle(1)
  })
  // 无法播放处理 
  let times = null // 避免重复回调
  music.onError((err) => {
    if (times) return
    times = setTimeout(() => {
      // 歌曲无版权
      uni.showModal({
        showCancel: false,
        content: '歌曲暂无版权，是否切换下一首歌曲',
        success() {
          toggle(1)
          times = null
        }
      })
    }, 500)

  })
  music.onTimeUpdate(() => {
    if (end.value !== music.duration) {
      end.value = parseInt(music.duration)
    }
    start.value = parseInt(music.currentTime)
  })
  const formatTime = (time) => {
    let m = parseInt(time / 60)
    m = m < 10 ? '0' + m : m
    let s = time % 60
    s = s < 10 ? '0' + s : s
    return m + ":" + s
  }
  const stepMisic = (e) => { // 跳转指定位置
    music.offTimeUpdate()
    start.value = e.detail.value
    music.pause()
    music.seek(e.detail.value)
    music.play()
    // 跳转会自动改为播放状态
    state.value = false
  }
  music.onSeeked(() => {
    music.onTimeUpdate(() => {
      if (end.value !== music.duration) {
        end.value = parseInt(music.duration)
      }
      start.value = parseInt(music.currentTime)
    })
  })

  // music.onCanplay(()=>{
  //   console.log(123);
  //   music.onPlay()
  // })
  // 音频由于网络等原因等待中的回调
  const waitFlag = ref('false')
  // music.onWaiting(() => {
  //   console.log('缓冲');
  //   music.pause() // 等待网络的时候音频暂停
  //   waitFlag.value = true
  // })
  // 音频准备就绪的回调
  // music.onCanplay(() => {
  //   if (waitFlag.value) { // 如果是onWaiting触发的暂停，就立即播放
  //     music.play() // play()方法看上去能重新触发onTimeUpdate()回调
  //     waitFlag.value = false
  //   }
  // })
  // 退出页面要注销所有监听
  onUnmounted(() => {
    music.offPlay()
    music.offCanplay()
    music.offWaiting()
    music.offTimeUpdate()
    music.offSeeked()
    music.offError()
  })
  const linearColor1 = ref(null)
  const linearColor2 = ref(null)
  
  const bgToggle = ref(false)
  // watch(playItem,()=>{
  //   if (bgToggle.value) {
  //     linearColor1.value = playItem.value.al.picUrl
  //   } else {
  //     linearColor2.value = playItem.value.al.picUrl
  //   }
  //   bgToggle.value = !bgToggle.value
  // })
  const changeBg=(e)=>{
    toggleMusic(e)
    if (bgToggle.value) {
      linearColor1.value = playItem.value.al.picUrl
    } else {
      linearColor2.value = playItem.value.al.picUrl
    }
    bgToggle.value = !bgToggle.value  
  }
  // const canvas = wx.createCanvasContext('canvas', _this)
  // const changeBg = () => {
  //   const url = playItem.value.al.picUrl
  //   // 获取图片信息
  //   wx.getImageInfo({
  //     src: url, // 填写图片url或本地路径
  //     success: function(res) {
  //       // 此时已获取到图片真实宽高信息
  //       canvas.drawImage(res.path, 0, 0, 100, 100) // 将图片绘制到画布上
  //       canvas.draw(false, () => {
  //         wx.canvasGetImageData({
  //           canvasId: 'canvas',
  //           x: 0,
  //           y: 0,
  //           width: res.width,
  //           height: res.height,
  //           success: function(res) {
  //             // 此时已获取到画布像素数据
  //             const data = res.data
  //             const num = res.height * res.width
  //             const arr = createPixelArray(data, num)
  //             const count = {}
  //             arr.forEach((v, i) => {
  //               if (count[v]) {
  //                 count[v]++
  //               } else {
  //                 count[v] = 1
  //               }
  //             })
  //             delete count['0,0,0']
  //             const sortable = []
  //             for (let key in count) {
  //               sortable.push([key, count[key]])
  //             }
  //             sortable.sort((a, b) => {
  //               return b[1] - a[1]
  //             })
  //             const mainColors = sortable.slice(0, 5);
             
  //           }
  //         })
  //       })
  //     }
  //   })
  // }

  // function createPixelArray(imgData, pixelCount, quality = 10) {
  //   const pixels = imgData;
  //   const pixelArray = [];
  //   for (let i = 0, offset, r, g, b, a; i < pixelCount; i = i + quality) {
  //     offset = i * 4;
  //     r = pixels[offset + 0];
  //     g = pixels[offset + 1];
  //     b = pixels[offset + 2];
  //     a = pixels[offset + 3];

  //     // If pixel is mostly opaque and not white
  //     pixelArray.push([r, g, b]);
  //   }
  //   return pixelArray;
  // }
</script>

<style lang="less">
  page {
    height: 100%;
  }
  .detail-wrap {
    height: 100%;
    display: flex;
    overflow: hidden;
    flex-direction: column;
    justify-content: space-between;
    position: relative;
    background-color: #f5f5f5;
    z-index: 1;

    .bg1,
    .bg2 {
      position: absolute;
      top: 0;
      transform: scale(2.5) ;

      width: 100%;
      height: 100%;

      z-index: -1;
      filter: blur(25rpx);
      transition: opacity 3s;
       // transform: translateZ(0);
       backface-visibility: hidden;
    }

    .bg1 {
      opacity: 1;

      &.active {
        opacity: 0;
      }
    }

    .bg2 {
      opacity: 0;

      &.active {
        opacity: 1;
      }
    }

    .header {
      // box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 15rpx 32rpx;
      height: 91rpx;

      .info {
        flex: 1;
        padding: 0 150rpx;
        text-align: center;

        .uni-noticebar {
          margin-bottom: 0;
          padding: 0 12px;
        }

        .name {
          font-size: 30rpx;
          color: #fff;
        }

        .artist {
          font-size: 28rpx;
          color: rgba(255, 255, 255, 0.7);
        }
      }

    }

    @keyframes rotation {
      0% {
        -webkit-transform: rotate(0deg);
      }

      100% {
        -webkit-transform: rotate(360deg);
      }
    }

    swiper {
      height: 700rpx;

    }

    .bg {
      display: block;
      width: 320rpx;
      height: 320rpx;
      border-radius: 50%;
      border: 70rpx solid #000;
      margin: 100rpx auto;
      animation: rotation 15s linear infinite;
    }
  }

  .pus_img {
    animation-play-state: paused !important;
    -webkit-animation-play-state: paused !important;
  }

  .control {
    // background-color: #e0d865;
    // margin-top: 260rpx;

    .icons {
      padding: 28rpx 15rpx;
      display: flex;
      justify-content: space-around;
      align-items: center;
    }

    .time-box {
      display: flex;
      padding: 0 34rpx;
      font-size: 12px;
      justify-content: space-between;
      align-items: center;

      slider {
        flex: 1;
      }
    }
  }
</style>


// 数据结构
<!-- 目标元素 index0  加入循环circular
  [[七月][八月][六月]]
  向右滑
  [[七月][八月][九月]]
  向右滑
  [[十月][八月][九月]] -->
